<template>
  <div class="app-container">

    <el-card class="box-card">
      <h3>商品介绍</h3>
      <el-form ref="goods" :rules="rules" :model="goods" label-width="150px">
        <el-form-item v-if="false" label="商品ID" prop="pid">
          <el-input v-model="goods.pid" disabled />
        </el-form-item>
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="goods.productName" />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="goods.price" placeholder="0.00">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="商品图片">
          <el-upload :file-list="fileList" ref="uploadRef" action="#" :limit="1" list-type="picture-card"
            class="avatar-uploader" :class="{ isFileHide: goods.pic }" accept=".jpg,.jpeg,.png" :on-remove="handleRemove"
            :http-request="handleUpload" :before-upload="beforeUpload">
            <i slot="default" class="el-icon-plus" />
            <div slot="file" slot-scope="{file}">
              <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
              <span class="el-upload-list__item-actions">
                <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                  <i class="el-icon-zoom-in" />
                </span>
                <span class="el-upload-list__item-delete" @click="handleRemove(file)">
                  <i class="el-icon-delete" />
                </span>
              </span>
            </div>

          </el-upload>
        </el-form-item>
        <el-form-item label="所属分类" prop="productTypeId">
          <el-select v-model="goods.productTypeId" placeholder="请选择商品分类">
            <el-option v-for="(item, index) in categoryList" :label="item.label" :value="item.value"
              :key="index"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品详细介绍">
          <editor v-model="goods.description" :init="editorInit" />
        </el-form-item>
      </el-form>
    </el-card>
    <div class="op-container">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleEdit">更新商品</el-button>
    </div>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>
<script>
import { detailGoods, editGoods, getDetailInfo } from '@/api/goods'
import { listCategory } from '@/api/category'
import { uploadFileUnParam } from '@/api/file'
import Editor from '@tinymce/tinymce-vue'
import { MessageBox } from 'element-ui'
import { getToken } from '@/utils/auth'
import Cookies from 'js-cookie'

export default {
  name: 'GoodsEdit',
  components: { Editor },
  data() {
    return {
      dialogVisible: false,
      dialogImageUrl: '',
      fileList: [],
      categoryList: [],
      goods: { gallery: [] },
      productVisiable: false,
      rules: {
        name: [{ required: true, message: '商品名称不能为空', trigger: 'blur' }]
      },
      editorInit: {
        language: 'zh_CN',
        height: '400px',
        convert_urls: false,
        plugins: [
          'advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools importcss insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount'
        ],
        toolbar: [
          'searchreplace bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript code codesample',
          'hr bullist numlist link image charmap preview anchor pagebreak insertdatetime media table emoticons forecolor backcolor fullscreen'
        ],
        images_upload_handler: function (blobInfo, success, failure) {
          const formData = new FormData()
          formData.append('file', blobInfo.blob())
          uploadFileUnParam(formData)
            .then(res => {
              success(res.data.data.url)
            })
            .catch(() => {
              failure('上传失败，请重新上传')
            })
        }
      }
    }
  },
  computed: {
    headers() {
      return {
        'X-Litemall-Admin-Token': getToken()
      }
    },
  },
  created() {
    this.init()
    this.getCateGoryList()
  },
  methods: {
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
      this.goods.pic = ''
      this.fileList = []
      this.$refs.uploadRef.clearFiles()
    },
    handlePreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 选择文件确认上传
    beforeUpload(file) {
      const fileType = file.name.substring(file.name.lastIndexOf(".") + 1);
      const allowFileType = ["jpg", "png", "jpeg"];
      if (allowFileType.indexOf(fileType) === -1) {
        this.$message.error("附件仅支持jpg/png/jpeg格式");
        return false;
      }
      const limit = file.size / 1024 / 1024 < 2;
      if (!limit) {
        this.$message.error("上传文件大小不能超过 2MB!");
      }
      return limit;
    },
    // 文件上传接口
    handleUpload(file) {
      this.goods.pic = '111'
      const fromData = new FormData()
      fromData.append('file', file.file)
      uploadFileUnParam(fromData).then(res => {
        console.log(res)
        if (res.code === 200) {
          this.goods.pic = res.data.fileUrl
          this.fileList.push({ name: '', url: res.data.fileUrl })
          // this.$message.success('图片上传成功')
        } else {
          this.goods.pic = ''
        }
      }).catch(err => {
        console.log(err)
        this.goods.pic = ''
      })
    },
    //获取所属分类
    getCateGoryList() {
      let params = {
        shopId: Cookies.get("shopId")
      }
      listCategory(params).then((res) => {
        if (res.code === 200) {
          console.log('res.data', res.data);
          let result = res.data
          this.categoryList = result.map(item => {
            return {
              label: item.productTypeName,
              value: item.productTypeId
            }
          })
        }
      })
    },
    init() {
      if (this.$route.query.id == null) {
        return
      }
      let params = {
        pid: this.$route.query.id
      }
      getDetailInfo(params).then(response => {
        this.goods = response.data
        this.goods.pic = response.data.pic
        this.fileList.push({ name: "", url: response.data.pic })
      })
    },
    handleCancel: function () {
      this.$store.dispatch('tagsView/delView', this.$route)
      this.$router.push({ path: '/goods/list' })
    },
    handleEdit() {
      let params = {
        ...this.goods
      }
      editGoods(params)
        .then(response => {
          this.$notify.success({
            title: '成功',
            message: '编辑成功'
          })
          this.$store.dispatch('tagsView/delView', this.$route)
          this.$router.push({ path: '/goods/list' })
        })
        .catch(response => {
          MessageBox.alert('业务错误：' + response.data.errmsg, '警告', {
            confirmButtonText: '确定',
            type: 'error'
          })
        })
    },
    handleClose(tag) {
      this.keywords.splice(this.keywords.indexOf(tag), 1)
      this.goods.keywords = this.keywords.toString()
    },
    uploadPicUrl: function (response) {
      this.goods.picUrl = response.data.url
    },
    uploadOverrun() {
      this.$message({
        type: 'error',
        message: '上传文件个数超出限制!最多上传5张图片!'
      })
    },
  }
}
</script>
<style>
.app-container {
  height: auto;
}

.el-card {
  margin-bottom: 10px;
}

.el-tag+.el-tag {
  margin-left: 10px;
}

.input-new-keyword {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.avatar {
  width: 145px;
  height: 145px;
  display: block;
}

.op-container {
  display: flex;
  justify-content: center;
}


.avatar-uploader .el-upload {
  width: 145px;
  height: 145px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.isFileHide .el-upload--picture-card {
  display: none !important;
}

.isFileHide div {
  width: 100%;
  height: 100%;
}
</style>